import config from '../../mars/conf/config'
var api = require("../../mars/services/api.js");
let that;
let daysCalenders = [];
for (let i = 1; i < 22; i++) {
  daysCalenders.push(i);
}
Component({
  pageLifetimes: {
    show() {
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 2
        });
      }
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    host: config.domain + "/uploads/food-templates/",
    toViewId: "scroll-view_1",
    daysCalenders: daysCalenders,
    animationData: {
      breakfast: {
        animation: {},
        visible: "hidden",
        supplementFood: []
      },
      lunch: {
        animation: {},
        visible: "hidden",
        supplementFood: []
      },
      supper: {
        animation: {},
        visible: "hidden",
        supplementFood: []
      },
    },
    curTotalCalorie: {
      breakfast: 0,
      lunch: 0,
      supper: 0
    },
    target: {
      breakfast: 0,
      lunch: 0,
      supper: 0,
    },
    calorie: "",
    calorieColor: "is-white",
    mealActive: "lunch",
    meal: {
      breakfast: {
        mainFood: [],
        supplementFood: [],
      },
      lunch: {
        mainFood: [],
        supplementFood: [],
      },
      supper: {
        mainFood: [],
        supplementFood: [],
      }
    },
    showActivityTag: false,
    activityInfo: {},
    showActivityBtn: false,
    alreadyPartIn: false,
  },

  methods: {
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
      that = this;

      that.setData({
        mealActive: "breakfast"
      });
      wx.setStorageSync("breakfast", null);
      wx.setStorageSync("lunch", null);
      wx.setStorageSync("supper", null);
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
      console.log('onShow');
      let value = wx.getStorageSync('calorie');
      if (!value) {
        wx.navigateTo({
          url: '/pages/calorieSet/calorieSet',
        });
        return;
      }

      that.setData({
        target: {
          breakfast: Math.round(value * 0.3),
          lunch: Math.round(value * 0.4),
          supper: Math.round(value * 0.3),
        },
        calorie: value,
        userId: wx.getStorageSync('user').id
      });
      that.refreshData(that.data.mealActive, value);
    },
    getMenuListByMealName(e) {
      let meal = that.data.mealActive;
      let value = wx.getStorageSync('calorie');
      that.refreshData(meal, value, 1);
    },
    refreshData(mealName, value, force) {
      let mealData = wx.getStorageSync(mealName);

      // if had and not force , get IT in cache from local
      if (!force && mealData) {
        let curTotalCalorie = wx.getStorageSync('curTotalCalorie');
        that.data.meal[mealName] = mealData;
        that.setData({
          meal: that.data.meal,
          curTotalCalorie: curTotalCalorie
        });
        return;
      }

      let mealType = that.data.mealActive;
      this.getUserEventByUserId(that.data.userId).then((data) => {
        if (data.length) {
          let eventId = data[0].event_id;
          let joinDate = data[0].join_date;
          let offsetDay = that.getRandomDay(1,21);
          that.setData({
            currentDay: offsetDay,
            eventId: eventId
          });
          get21DayMeal(eventId, that.data.currentDay, mealType);
        } else {
          // 没有参加活动, 获取活动详情
          // getOriginalMeal(that.data.calorie, mealName, that.data.userId);
          that.getAllAvailbleEvents().then((res) => {
            if (res.length) {
              let eventId = res[0].id;
              that.setData({
                currentDay: that.getRandomDay(1, 21),
                eventId: eventId
              });
              get21DayMeal(eventId, that.data.currentDay, mealType);
            }
          })
        }
      });


      // 获取7天食谱
      function get21DayMeal(evnetId, days, mealType) {
        that.getMenuListByEventId(evnetId, days, mealType).then(data => {
          let responseData = data;
          that.mergeDataFromResponse(responseData[0] || {}, mealName);
        });
      }

      // 获取原本的食谱
      function getOriginalMeal(calorie, mealName, userId) {
        api.WxRequest(api.getFoodByType, {
          calorie: calorie,
          isRandom: true,
          mealType: mealName,
          userId: userId
        }, function(res) {
          let responseData = res.data;
          that.mergeDataFromResponse(responseData, mealName);
        });
      }
    },
    mergeDataFromResponse: function(responseData, mealName) {
      // 封装返回数据
      let data = {};
      let nullMeal = {
        mainFood: {},
        supplementFood: []
      };
      // if (!responseData.menu_templates) return;
      let mainFood = responseData.menu_templates && responseData.menu_templates.filter(item => {
        return item.food_order == 1
      }) || [];
      let supplementFood = responseData.menu_templates && responseData.menu_templates.filter(item => {
        return item.food_order != 1
      }) || [];

      that.data.animationData[that.data.mealActive].supplementFood = supplementFood.map(item => {
        return {
          visible: "hidden",
          animation: {}
        }
      });
      let mealData = {
        mainFood: mainFood[0],
        supplementFood: supplementFood,
        animationData: that.data.animationData,
      };
      that.data.meal[mealName] = mealData;
      data.meal = that.data.meal;
      data.mealActive = mealName;

      that.data.curTotalCalorie[mealName] = responseData.kcal;
      data.curTotalCalorie = that.data.curTotalCalorie;
      that.setData(data);

      wx.setStorageSync('curTotalCalorie', that.data.curTotalCalorie);
      wx.setStorageSync(mealName, mealData);
    },
    navigate: function(data) {
      wx.navigateTo({
        url: '/pages/calorieFoodSort/calorieFoodSort?meal=' + that.data.mealActive
      });
    },
    changeToMeal(e) {
      let meal = e.currentTarget.dataset.meal;
      that.setData({
        mealActive: meal
      })
      let value = wx.getStorageSync("calorie");
      that.refreshData(meal, value);
    },
    nevitageToPunchsCircle() {
      wx.navigateTo({
        url: '/pages/communityIndex/communityIndex'
      });
    },

    navigateToSetInfo() {
      wx.navigateTo({
        url: '/pages/calorieSet/calorieSet'
      });
    },
    calorieFoodDetail(e) {
      let menuname = e.currentTarget.dataset.menuname;
      wx.navigateTo({
        url: '/pages/calorieMenuName/calorieMenuName?foodName=' + menuname +
          "&mealName=" + that.data.mealActive +
          "&calorie=" + that.data.calorie
      })
    },
    toggleAnimationVisible(e) {
      let height = +e.currentTarget.dataset.height;
      let mealName = e.currentTarget.dataset.meal;
      let foodtype = e.currentTarget.dataset.foodtype;
      let supplementFoodIdx = e.currentTarget.dataset.foodtypeidx;
      let visibleState = foodtype ? that.data.animationData[mealName].visible : that.data.animationData[mealName].supplementFood[supplementFoodIdx].visible;
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      });
      // that.data.animationData[mealName].animation = animation;

      if (visibleState == 'hidden') {
        animation.height(height).step();

        if (foodtype == 'mainFood') {
          that.data.animationData[mealName].animation = animation.export();
          that.data.animationData[mealName].visible = 'shown';
        } else {
          that.data.animationData[mealName].supplementFood[supplementFoodIdx].animation = animation.export();
          that.data.animationData[mealName].supplementFood[supplementFoodIdx].visible = 'shown';
        }

        that.setData({
          animationData: that.data.animationData
        })
      } else {
        animation.height(0).step();

        if (foodtype == 'mainFood') {
          that.data.animationData[mealName].animation = animation.export();
          that.data.animationData[mealName].visible = 'hidden';
        } else {
          that.data.animationData[mealName].supplementFood[supplementFoodIdx].animation = animation.export();
          that.data.animationData[mealName].supplementFood[supplementFoodIdx].visible = 'hidden';
        }
        that.setData({
          animationData: that.data.animationData
        })
      }
    },
    joinInGroup(groupId) {
      api.WxRequest(api.partInGroup, {
        groupId: groupId,
        userId: wx.getStorageSync('user').id
      }, (res) => {
        if (res.status) return;
        wx.showToast({
          title: '已接收邀请,加入小组'
        });
      });
    },
    getUserEventByUserId(userId) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getUserEventByUserId, {
          userId: userId
        }, (res) => {
          resolve(res.data);
        });
      });
    },
    getEventInfoByEventId(eventId) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getEventInfoByEventId, {
          eventId: eventId
        }, (res) => {
          resolve(res.data);
        });
      })
    },
    partInEvent(userId, eventId) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.partInEvent, {
          userId: userId,
          eventId: eventId
        }, (res) => {
          resolve(res.data);
        });
      })
    },
    getMenuListByEventId(eventId, day, mealType) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getMenuListByEventId, {
          eventId,
          day,
          mealType
        }, (res) => {
          resolve(res.data);
        });
      })
    },
    getAllAvailbleEvents() {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getAllAvailbleEvents, {}, (res) => {
          resolve(res.data);
        });
      })
    },
    partInActivity() {
      wx.showLoading({
        title: '正在加载中',
      });
      that.partInEvent(that.data.userId, that.data.activityInfo.id).then(data => {
        wx.hideLoading();
        wx.showToast({
          title: '参加活动成功',
          icon: "none"
        });

        that.setData({
          showActivityTag: false,
          alreadyPartIn: true
        });

        that.getMenuListByMealName();
      })
    },
    hoverToViewDay(e) {
      let viewnum = e.target.dataset.viewnum;
      that.setData({
        toViewId: "scroll-view_" + viewnum
      });

      that.getMenuListByEventId(that.data.evnetId, viewnum, that.data.mealActive).then(data => {
        let responseData = data;
        that.mergeDataFromResponse(responseData[0] || {}, that.data.mealActive);
      });
    },
    scroll() {
      // 滚动
    },
    getRandomDay(start, end){
      let day = parseInt(Math.random()*21);
      return day;
    }
  }
})